package com.zl.controller;


import com.zl.common.Result;
import com.zl.dto.TsUserDto;
import com.zl.security.SecurityUtils;
import com.zl.service.UserService;
import com.zl.util.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("user")
public class UserController {

    private static SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");
    public final static String PATH_PREFIX = "static/upload";
    @Autowired
    private UserService userService;

    @PostMapping(value = "/users")
   // @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_CREATE')")
    public Result create(@RequestBody TsUserDto resources){
        return userService.create(resources);
    }

    @PutMapping(value = "/users")
    //@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_EDIT')")
    public Result update(@RequestBody TsUserDto resources){
        return userService.update(resources);
    }

    @DeleteMapping(value = "/users/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_DELETE')")
    public Result delete(@PathVariable Long id){
        return userService.delete(id);
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping(value = "/users/updatePass")
    public Result updatePass(@RequestBody TsUserDto user){
        UserDetails userDetails = SecurityUtils.getUserDetails();
        if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getOldPass()))){
            return Result.error("修改失败，旧密码错误");
        }
        String newPaas = EncryptUtils.encryptPassword(user.getNewPass());
        if(userDetails.getPassword().equals(newPaas)){
            return Result.error("新密码不能与旧密码相同");
        }
        return userService.updatePass(userDetails.getUsername(),newPaas);
    }

    /**
     * 修改头像
     * @param file
     * @return
     */
    @PostMapping(value = "/users/updateAvatar")
    public Result updateAvatar(@RequestParam MultipartFile file){
        if (file.isEmpty()) {
            return Result.error("修改头像失败，请选择文件");
        }
        // 拿到文件名
        String filename = file.getOriginalFilename();
        int idx = filename.lastIndexOf(".");
        String extention = filename.substring(idx);
        String time = SDF.format(new Date());

        //新的文件名(日期+后缀)
        filename = filename.substring(0, idx) + time + extention;
        try{

            // 构建真实的文件路径
            File newFile = new File(getPath() + File.separator + filename);
            // 上传图片到 -》 “绝对路径”
            file.transferTo(newFile);
            return userService.updateAvatar(SecurityUtils.getUsername(),getPath() + File.separator + filename);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("修改头像失败");
        }

    }

    private static String getPath() throws FileNotFoundException {
        //首先获取根目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        //然后获取需要的目录，我们设定我们需要将文件存放在与jar包同级的static的upload目录下
        File upload = new File(path.getAbsolutePath(), PATH_PREFIX);
        if (!upload.exists()) {
            upload.mkdirs();
        }
        return upload.getAbsolutePath();
    }

    /**
     * 修改邮箱
     * @param user
     * @param user
     * @return
     */
    /*@PostMapping(value = "/users/updateEmail/{code}")
    public Result updateEmail(@PathVariable String code,@RequestBody TsUserDto user){
        UserDetails userDetails = SecurityUtils.getUserDetails();
        if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
            return Result.error("密码错误");
        }
        VerificationCode verificationCode = new VerificationCode(code, ElAdminConstant.RESET_MAIL,"email",user.getEmail());
        verificationCodeService.validated(verificationCode);
        userService.updateEmail(userDetails.getUsername(),user.getEmail());
        return new ResponseEntity(HttpStatus.OK);
    }*/
}